import { css } from '@emotion/css';
import { useState } from 'react';

import { GrafanaTheme2 } from '@grafana/data';
import { t } from '@grafana/i18n';
import { useStyles2 } from '@grafana/ui';
import { useGrafana } from 'app/core/context/GrafanaContext';
import { contextSrv } from 'app/core/core';

import { BreadcrumbItem } from './BreadcrumbItem';
import { Breadcrumb } from './types';

export interface Props {
  breadcrumbs: Breadcrumb[];
  className?: string;
}

export function Breadcrumbs({ breadcrumbs, className }: Props) {
  const styles = useStyles2(getStyles);

  const { chrome } = useGrafana();

  const [navClickEvent, setNavClickEvent] = useState(false);
  const handleNavigationClick = (navigation: string) => {
    chrome.setMegaMenuOpen(false);
    chrome.setMegaMenuOpen(true);
    localStorage.setItem('grafana.navigation', navigation);
    window.dispatchEvent(new Event('localStorageChange'));
    if (navigation === "Welcome") {
      // chrome.setMegaMenuDocked(true, false);
      chrome.setMegaMenuOpen(false);
    }
    setNavClickEvent(true);
  };

    //新用户默认Docked
  if (localStorage.getItem('grafana.navigation.docked') === null) {
    localStorage.setItem('grafana.navigation.docked', "true");
  }
  if (localStorage.getItem('grafana.navigation') === "Welcome") {
    chrome.setMegaMenuOpen(false);
  }

  //通过breadcrumbs来控制左侧导航栏的显示
  let Nav: string | null = "";
  for (let i = 0; i < breadcrumbs.length; i++) {
    if (breadcrumbs[i].href === "/dashboards" && i < breadcrumbs.length - 1) {
      Nav = breadcrumbs[i + 1].text;
      break;
    }
  }
  //const Title = breadcrumbs[breadcrumbs.length-1].text;

  //当非点击导航栏时
  if (!navClickEvent) {
    //报警中心默认放入风险治理
    if (window.location.href.includes('/alerting/')) {
      Nav = "风险管理"
    }
    if (localStorage.getItem('grafana.navigation') !== "Manage" && Nav !== "") {
      localStorage.setItem('grafana.navigation', Nav);
    }
    if (Nav === "Welcome" || Nav === "应用中心" || Nav === "_Public_Libray") {
      chrome.setMegaMenuDocked(false, false);
      chrome.setMegaMenuOpen(false);
    }

  }

  if (localStorage.getItem('grafana.navigation.docked') === "true" && Nav !== "Welcome" && Nav !== "_Public_Libray" && Nav !== "应用中心" && localStorage.getItem('grafana.navigation') !== "Welcome" && localStorage.getItem('grafana.navigation') !== "应用中心" && localStorage.getItem('grafana.navigation') !== "_Public_Libray") {
    chrome.setMegaMenuDocked(true, false);
    chrome.setMegaMenuOpen(true);
  }

  return (
    <nav aria-label={t('navigation.breadcrumbs.aria-label', 'Breadcrumbs')} className={className}>
      <div id="navbuttons" className={styles.breadcrumbs}>
        <a id="navhomelink" className={`${localStorage.getItem('grafana.navigation') === 'Home' || localStorage.getItem('grafana.navigation') === '应用中心' || localStorage.getItem('grafana.navigation') === "Welcome" ? styles.linkButtonActive : styles.linkButton}`} href='/' onClick={() => { handleNavigationClick('Welcome'); }} >&nbsp;首页&nbsp;</a>｜
        <button className={`${localStorage.getItem('grafana.navigation') === '基础运维' ? styles.linkButtonActive : styles.linkButton}`} onClick={() => { handleNavigationClick('基础运维'); }}>&nbsp;基础运维&nbsp;</button>｜
        <button className={`${localStorage.getItem('grafana.navigation') === '成本运营' ? styles.linkButtonActive : styles.linkButton}`} onClick={() => { handleNavigationClick('成本运营'); }}>&nbsp;成本运营&nbsp;</button>｜
        <button className={`${localStorage.getItem('grafana.navigation') === '风险管理' ? styles.linkButtonActive : styles.linkButton}`} onClick={() => { handleNavigationClick('风险管理'); }}>&nbsp;风险管理&nbsp;</button>｜
        <button className={`${localStorage.getItem('grafana.navigation') === '业务观测' ? styles.linkButtonActive : styles.linkButton}`} onClick={() => { handleNavigationClick('业务观测'); }}>&nbsp;业务观测&nbsp;</button>｜
        <button className={`${localStorage.getItem('grafana.navigation') === '厂内工具' ? styles.linkButtonActive : styles.linkButton}`} onClick={() => { handleNavigationClick('厂内工具'); }}>&nbsp;厂内工具&nbsp;</button>
        {['Admin', 'Edit'].includes(contextSrv.user.orgRole) && (<> ｜ <a href='/dashboards' className={`${localStorage.getItem('grafana.navigation') === 'Manage' ? styles.alinkActive : styles.linkButton}`} onClick={() => { handleNavigationClick('Manage'); }}>&nbsp;后台面板&nbsp;</a> </>)}
      </div>
      <ol className={styles.breadcrumbs} style={{ display: 'none' }}>
        {breadcrumbs.map((breadcrumb, index) => (
          <BreadcrumbItem
            {...breadcrumb}
            isCurrent={index === breadcrumbs.length - 1}
            key={index}
            index={index}
            flexGrow={getFlexGrow(index, breadcrumbs.length)}
          />
        ))}
      </ol>
    </nav>
  );
}

function getFlexGrow(index: number, length: number) {
  if (length < 5 && index > 0 && index < length - 2) {
    return 4;
  }

  if (length > 6 && index > 1 && index < length - 3) {
    return 4;
  }

  return 10;
}

const getStyles = (theme: GrafanaTheme2) => {
  return {
    breadcrumbs: css({
      display: 'flex',
      alignItems: 'center',
      flexWrap: 'nowrap',
      overflow: 'hidden',
    }),
  linkButton: css({
      display: 'inline',
      background: 'none',
      border: 'none',
      color: 'inherit',
      textDecoration: 'none',
      cursor: 'pointer',
      padding: 0,
      margin: 0,
      font: 'inherit',
      outline: 'none',
    }),
    linkButtonActive: css({
      display: 'inline',
      background: 'none',
      border: 'none',
      color: 'inherit',
      textDecoration: 'none',
      cursor: 'pointer',
      padding: 0,
      margin: 0,
      font: 'inherit',
      outline: 'none',
      fontWeight: 'bold',
      backgroundImage: 'linear-gradient(90deg, #67c7fc -31.2%, #0080ff 113.07%)',
      backgroundRepeat: 'no-repeat',
      backgroundSize: '100% 1px',
      backgroundPosition: 'bottom',
    }),
    alinkActive: css({
      display: 'inline',
      background: 'none',
      border: 'none',
      color: 'inherit',
      textDecoration: 'none',
      cursor: 'pointer',
      padding: 0,
      margin: 0,
      font: 'inherit',
      outline: 'none',
      fontWeight: 'bold',
      backgroundImage: 'linear-gradient(90deg, #67c7fc -31.2%, #0080ff 113.07%)',
      backgroundRepeat: 'no-repeat',
      backgroundSize: '100% 1px',
      backgroundPosition: 'bottom',
      // paddingBottom: '3px'
    }),
    navBarcss: css({
      maxWidth: '60vw',
      minWidth: '100px',
      overflowX: 'auto', // 允许横向滚动
      whiteSpace: 'nowrap', // 防止文本换行
      WebkitOverflowScrolling: 'touch', // 优化移动端滚动效果
      MsOverflowStyle: '-ms-autohiding-scrollbar', // 在需要时隐藏滚动条（针对IE和Edge）
      scrollbarWidth: 'none', // Firefox中隐藏滚动条
      '&::-webkit-scrollbar': {
        display: 'none', // Chrome和Safari中隐藏滚动条
      },
    }),
  };
};
